class ExitBot(GridBot):
	def __init__(self):
		GridBot.__init__(self)
		
	def iterate(self):
		GridBot.iterate(self)
		if self.delay > 0: self.delay -= 1
		else:
			exitDirection = self.getExitDirection()
			#direction = self.getAvoidDirection(exitDirection)
			if self.getOut and self.look(exitDirection[0], exitDirection[1], GridBot):
				possibleDirections = self.getPossibleDirections()
				if len(possibleDirections) > 0:
					randomDirection = random.randint(0, len(possibleDirections) - 1)
					self.walk(possibleDirections[randomDirection][0], 
							  possibleDirections[randomDirection][1])
			else: self.walk(exitDirection[0], exitDirection[1])			  
			self.delay = self.maxDelay	
			
	def getExitDirection(self):
		x = "Center"
		z = "Center"
		if self.getLocation()[0] < self.exit[0]: x = "Right"
		if self.getLocation()[0] > self.exit[0]: x = "Left"
		if self.getLocation()[2] < self.exit[2]: z = "Down"
		if self.getLocation()[2] > self.exit[2]: z = "Up"
		return [x, z]	
		
	def getPossibleDirections(self):	
		possibleDirections = [["Left", "Up"],["Center", "Up"],["Right", "Up"],
		              ["Left", "Center"],["Center", "Center"],["Right", "Center"],
					  ["Left", "Down"],["Center", "Down"],["Right", "Down"]]
		
		directions = []
		while len(possibleDirections) > 0:
			direction = possibleDirections.pop()
			if (not self.look(direction[0], direction[1], GridBot) and
			    not self.look(direction[0], direction[1], Wall)):
					directions.append(direction)
		
		return directions	
		
	def getAvoidDirection(self, exitDirection):
		directions = self.getPossibleDirections()
		exitPosition = self.getPosition(exitDirection)
		exitVector = breve.vector(exitPosition[0], 0, exitPosition[1])	
		
		avoidVectors = []
		while len(directions) > 0:
			avoidPosition = self.getPosition(directions.pop())
			avoidVectors.append(self.exit - breve.vector(avoidPosition[0], 0, avoidPosition[1]))
		
		minVector = 0
		for i in range(0, (len(avoidVectors) - 1)):
			if avoidVectors[i].length() < avoidVectors[i + 1].length():
				minVector = avoidVectors[i]
			else: minVector = avoidVectors[i + 1]	
		
		print minVector
		
		return self.getDirection([minVector[0], minVector[2]])	
		
	def getPosition(self, direction):
		x = 0
		z = 0
		
		if direction[0] == "Left": x = self.getLocation()[0] - self.unit
		if direction[0] == "Right": x = self.getLocation()[0] + self.unit
		if direction[1] == "Up": z = self.getLocation()[2] - self.unit
		if direction[1] == "Down": z = self.getLocation()[2] + self.unit
		
		return [x, z]
		
	def getDirection(self, units):
		x = "Center"
		z = "Center"
	
		if self.getLocation()[0] > units[0]: x = "Left"
		if self.getLocation()[0] < units[0]: x = "Right"
		if self.getLocation()[0] > units[1]: z = "Down"
		if self.getLocation()[0] < units[1]: z = "Up"
		
		return [x, z]